#!/usr/bin/env node

const WebSocket = require("ws");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const stream = require("./kaiscr");
const fs = require("fs");

const html = `<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Cyan's KaiLive implementation</title>
</head>
<body>
  <img alt="stream" />
</body>
<script>
  img = document.querySelector("img");
  socket = new WebSocket("ws://localhost:6900");
  socket.onmessage = ({ data }) => (img.src = data);
</script>
</html>`;

if (require.main === module) {
	if (!fs.existsSync("./index.html")) fs.writeFileSync("./index.html", html, "utf-8");

	const args = yargs(hideBin(process.argv))
		.usage(`usage: kaiscr.py [-h] [--host] [--port] [--websocket --ws] \n\n"Stream" the screen of a KaiOS/FFOS device`)
		.help("h")
		.alias("h", "help")
		.options({
			host: {
				description: "The host to connect to",
				requiresArg: true,
			},
			port: {
				description: "The port to connect to",
				requiresArg: true,
			},
			websocket: {
				alias: "ws",
				description: "The port to use for the websocket",
				requiresArg: true,
			},
		})
		.version(false)
		.parse();

	const { host = "localhost", port = 6000, websocket = 6900 } = args;
	let index = 0;

	const wss = new WebSocket.Server({ port: websocket });
	wss.on("connection", (ws) => {
		ws.on("message", (message) => {
			console.log(`Received message => ${message}`);
		});
		const stop = stream(
			(dataurl, stop) => {
				index++;
				ws.send(dataurl);
			},
			{ host, port }
		);
		ws.on("close", () => {
			stop();
			process.exit(0);
		});
	});
	const text = fs.readFileSync("./index.html", "utf8") || html;
	const formatted = text.replace(/WebSocket\("ws:\/\/localhost:(\d*)"\)/, `WebSocket("ws://localhost:${websocket}")`);
	if (formatted !== text) fs.writeFileSync("./index.html", formatted, "utf-8");
	console.log("websocket is now running! please open index.html in the browser...");
} else {
	throw Error("the script cannot be used as a nodejs module!");
}
